package top.heue.utils.base.util.view

import android.util.Log
import android.view.View
import androidx.databinding.BindingAdapter
import androidx.lifecycle.findViewTreeLifecycleOwner
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

object BindUtil {

    @BindingAdapter("click")
    @JvmStatic
    fun setClick(view: View, run: (View) -> Unit) {
        val scope = view.findViewTreeLifecycleOwner()?.lifecycleScope
        if (scope == null) {
            Log.w("BindUtil", "Scope == null，绑定点击事件失败")
            return
        }
        val flow = callbackFlow<View> {
            view.setOnClickListener {
                trySend(it)
            }
            awaitClose { view.setOnClickListener(null) }
        }
        flow.onEach {
            run(it)
        }.launchIn(scope)
    }
}